Using Modules 1: Core Modules
Okay, so let’s now write our very first Node code here inside a file and all I’m gonna do is to create a hello variable. And then putting the classic “Hello world” in there. So “Hello world” has been traditionally used when starting a new programming language and that’s kind of what we’re doing here. Okay, and now I’m logging to the console this hello variable, so very very very simple stuff.
Give it a save and let’s actually now run this file. So, in normal JavaScript in a browser, we would now include this JavaScript file into some HTML file and then open up that HTML file in a browser, right? But here with Node, we don’t need to do anything like that.
All we do is to use our Node command. But now, we’re not gonna hit ‘Enter’ right away, because that would take us back to the REPL but instead we want to run this file. And so all we have to do is to write Node and then the name of the file, so index.js, hit ‘Enter’ and indeed, here we have our log “Hello world.” So congratulations, you just ran your very first Node script.
Now, that isn’t really all that useful, is it? So let’s do something a bit more advanced. And remember how I said right in the first lecture that with Node.js, we can do all kinds of amazing things that we cannot do with JavaScript in the browser like for example reading files from the file system, right? Now in order to do that, we need to use a Node module. So Node.js is really built around this concept of modules where all kinds of additional functionality are stored in a module. And in the case for reading files, that is inside the FS module.
So how do we open up these modules, or how can we actually use them?
Well, we do require them into our code and then store the result of the requiring function in a variable. So that sounds a bit complicated, so let’s simply do it. So we will call FS to the result of requiring the FS module. And FS here stands for file system. So by using this module here, we will get access to functions for reading data and writing data right to the file system.
So again, calling this function here with this built-in FS module name will then return an object in which there are lots of functions that we can use. And restore that object right into the FS variable that we can then later use.
We are going to use it in the next lecture, but for now I want to quickly take a look at the Node documentation with you, so that in case you need some other module for yourself later, you always know where to look up some information about it. Okay, so the Node documentations are something really, really important for every Node developer to know about. So, what we do is to go to nodejs.org and then hit the documentations tab here and then select the Node version that you’re using here on the left side. And so that is the documentation. Here on the left side, you have all kinds of different modules.